import * as echarts from 'echarts';
import {LitElement, html, TemplateResult} from 'lit';
import {customElement, property} from "lit/decorators.js";
import style from '../echarts.css.ts';

export interface LoadingProps {
    chartId?: string;
    width?: string;
    height?: string;
    size?: number;
    color?: string;
}

@customElement('lit-loading')
export class LitLoading extends LitElement {
    @property({type: String}) chartId: string = 'lit-loading-chart';
    @property({type: String}) width: string = '200px';
    @property({type: String}) height: string = '100px';
    @property({type: Number}) size: number = 1;
    @property({type: String}) color: string = '#5470c6';

    getChildren(size: number, color: string): any[] {
        return new Array(7).fill(0).map((_val, i) => ({
            type: 'rect',
            x: i * 20 * size,
            shape: {
                x: 0,
                y: -40 * size,
                width: 10 * size,
                height: 80 * size
            },
            style: {
                fill: color,
            },
            keyframeAnimation: {
                duration: 1000,
                delay: i * 200,
                loop: true,
                keyframes: [
                    {
                        percent: 0.5,
                        scaleY: 0.3,
                        easing: 'cubicIn'
                    },
                    {
                        percent: 1,
                        scaleY: 1,
                        easing: 'cubicOut'
                    }
                ]
            }
        }))
    }

    option: echarts.EChartsOption = {
        graphic: {
            elements: [
                {
                    type: 'group',
                    left: 'center',
                    top: 'center',
                    children: this.getChildren(this.size, this.color),
                }
            ]
        }
    };

    static styles = style;

    updated(): void {
        (this.option.graphic! as any).elements![0].children = this.getChildren(this.size, this.color);
        this.firstUpdated();
    }

    firstUpdated() {
        const chart = echarts.init(this.shadowRoot!.getElementById(this.chartId)!);
        chart.setOption(this.option);
    }

    render(): TemplateResult {
        return html`<div id="${this.chartId}" style="width: ${this.width}; height: ${this.height};"></div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'lit-loading': LitLoading;
    }
}